package de.idgard.android.addon.ui.services.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import de.idgard.android.R;
import de.idgard.android.addon.ui.services.PropertiesService;
import de.idgard.android.addon.ui.services.UpdateService;

class UpdateServiceImpl implements UpdateService {

	private PropertiesService propertiesService;

	public void setPropertiesService(PropertiesService propertiesService) {
		this.propertiesService = propertiesService;
	}

	private String extractLatestVersion(final String url) throws Exception {
		BufferedReader in = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			while ((line = in.readLine()) != null) {
				sb.append(line);
				break;
			}
			in.close();
			return sb.toString().trim();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public String checkIfLatestVersionAndGetLinkUrl() {
		String currentVersion = propertiesService
				.getString(R.string.addonversion);
		String metadataFileUrl = propertiesService
				.getString(R.string.metadataBaseUpdateUrl)
				+ propertiesService.getString(R.string.metadataFileName);
		try {
			String latestVersion = extractLatestVersion(metadataFileUrl);
			if (!currentVersion.equals(latestVersion)) {
				return propertiesService
						.getString(R.string.metadataBaseUpdateUrl)
						+ latestVersion
						+ "/"
						+ propertiesService.getString(R.string.artifactName)
								.replace("${version}", latestVersion);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;
	}

}
